package com.harmontronics.app.pedestal.bridge;

import android.annotation.SuppressLint;
import android.location.Location;
import android.webkit.JavascriptInterface;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.LogUtils;
import com.google.gson.JsonObject;
import com.harmontronics.app.pedestal.agent.WebActivity;
import com.harmontronics.app.pedestal.bridge.model.BaseBridge;

import fr.quentinklein.slt.LocationTracker;
import fr.quentinklein.slt.ProviderError;
import wendu.dsbridge.CompletionHandler;

public class GpsBridge extends BaseBridge {

    private WebActivity activity;
    private LocationTracker locationTracker;
    private JsonObject result;

    public GpsBridge(WebActivity activity) {
        this.activity = activity;
        locationTracker = new LocationTracker();
    }

    @SuppressLint("MissingPermission")
    @JavascriptInterface
    public void start(Object argsJson, CompletionHandler<String> handler) {
        LogUtils.d("GPS.start");
        try {
            if (null != result) {
                handler.complete(success(result));
            }
            locationTracker.addListener(new LocationTracker.Listener() {
                @Override
                public void onLocationFound(@NonNull Location location) {
                    result = new JsonObject();
                    result.addProperty("latitude", location.getLatitude());
                    result.addProperty("longitude", location.getLongitude());
                    handler.complete(success(result));
                }

                @Override
                public void onProviderError(@NonNull ProviderError providerError) {
                    handler.complete(fail(providerError.getMessage(), providerError.getCause()));
                }
            });
            locationTracker.startListening(activity);
        } catch (Exception e) {
            handler.complete(fail(e.getMessage(), e));
        }
    }

    @JavascriptInterface
    public void stop(Object argsJson, CompletionHandler<String> handler) {
        LogUtils.d("GPS.stop");
        try {
            locationTracker.stopListening(true);
            handler.complete(success("GPS.stop success"));
        } catch (Exception e) {
            handler.complete(fail(e.getMessage(), e));
        }
    }
}
